<template>
    <div id="mapContainer"></div>
</template>

<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue';
import AMapLoader from '@amap/amap-jsapi-loader'
import location from '../../assets/icon/coord.png'
import axios from 'axios';
import { getLargeItem } from '@/utils';
import { getData } from '@/utils/indexedDBService';

interface Props {
    defects: any[],
    // zoomList: any[],
    mapMode: string,
}
const props = withDefaults(defineProps<Props>(), {
})

const emit = defineEmits(["clickMarker", "zoomChange"])

let map;
let AMap;
let customMarker;
let marker;
let cluster;
let styleList;

const cityName = ref()
// const zoomLevelValue = ref(10)

// watch(props.zoomList, (newValue, oldValue) => {
//     console.log(`zoomList prop changed from ${oldValue} to ${newValue}`);
//     // updateClusterNumber()
// });


const initMap = () => {
    AMapLoader.load({
        key: '05497d6de5c1d12b6a165644e05a10cf',
        version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [
            'AMap.ToolBar',
            'AMap.Scale',
            'AMap.HawkEye',
            'AMap.MapType',
            'AMap.MarkerClusterer',
            'AMap.MassMarks',
            'AMap.Geolocation',
            'AMap.DistrictSearch',
            'AMap.GeoJSON',
            'AMap.event',
            'AMap.CitySearch',
            'AMap.DistrictCluster',
            // 'AMap.DoubleClickZoom'
        ], // 需要使用的的插件列表
    })
        .then(_AMap => {
            AMap = _AMap
            findMask();
        })
        .catch(e => {
            console.log(e)
        })
}

const findMask = () => {
    // let center = []
    let cityName = ''
    var citySearch = new AMap.CitySearch()
    citySearch.getLocalCity(function (status, result) {
        if (status === 'complete' && result.info === 'OK') {
            // 查询成功，result即为当前所在城市信息
            console.log("citySearch onComplete 222==>", result)
            cityName = result.city
            // cityName.value = result.city
        }
    })

    // console.log('hihihi findMask')
    const district = new AMap.DistrictSearch({ subdistrict: 0, extensions: 'all', level: 'district' });
    district.search(cityName, (status, result) => {
        // 这里是整个边界经纬度
        // console.log('DistrictSearc result', result)
        // console.log('DistrictSearc result boundaries', result.districtList[0].boundaries)
        const bounds = result.districtList[0].boundaries
        const mask = []
        for (let i = 0; i < bounds.length; i++) {
            mask.push([bounds[i]])
        }
        // console.log('DistrictSearc mask', mask)
        setupMap(mask);
    });

}

const setupMap = (mask) => {
    // console.log('setupMap result', mask) // 这里是整个郑州市的边界经纬度
    const layers = props.mapMode == 'standard' ? [] : [
        new AMap.TileLayer(),//高德默认标准图层
        // 高德默认标准图层
        new AMap.TileLayer.Satellite(),
    ]

    map = new AMap.Map('mapContainer', {
        // mask: mask, // 为Map实例制定掩模的路径,各图层将值显示路径范围内图像,3D模式下有效
        resizeEnable: true, //是否监控地图容器尺寸变化
        zoom: 10, //初始化地图层级
        center: center,
        // center: [121.472644, 31.231706],
        // center: [111.096439, 36.411827], //初始化地图中心点，不设置中心点定位到当前城市中心
        mapStyle: 'amap://styles/b7c9e8d817a8886ad7a0ceec47cd7026',
        layers: layers,
        // layers: [
        //     new AMap.TileLayer(),//高德默认标准图层
        //     // 高德默认标准图层
        //     new AMap.TileLayer.Satellite(),
        //     // 楼块图层
        //     // new AMap.Buildings({
        //     //     zooms: [16, 18],
        //     //     zIndex: 10,
        //     //     heightFactor: 2//2倍于默认高度，3D下有效
        //     // })
        // ]
    });
    var center = map.getCenter();
    // emit('zoomChange', 10, [center.lng, center.lat])


    setMarkerClusterer(props.defects)


    // map.setCity(cityName.value);


    // //设置地图比例尺
    map.addControl(new AMap.Scale());

    let polygons = [];
    if (mask) {
        for (var i = 0, l = mask.length; i < l; i++) {
            //生成行政区划polygon
            var polygon = new AMap.Polygon({
                strokeWeight: 1,
                path: mask[i],
                fillOpacity: 0.05,
                fillColor: '#80d8ff',
                strokeColor: '#0091ea'
            });
            polygons.push(polygon);
        }
    }
    map.add(polygons)

    setupMarks();

}

const setupMarks = () => {
    // const points = props.defects.map((defect) => {
    //     // console.log("defect ==>", defect)
    //     return {
    //         "lnglat": [defect.longitude, defect.latitude],
    //         "extra": defect,
    //     }
    // });
    // let points = []
    // props.zoomList.map((item) => {
    //     console.log("item.defect_count ==.", item.defect_count)
    //     for (let i = 0; i < item.defect_count; i++) {
    //         points.push({
    //             "lnglat": [item.longitude, item.latitude],
    //             "extra": item,
    //         })
    //     }
    // });
    // console.log("points ==>", points)


    // cluster = new AMap.MarkerClusterer(map, points, {
    //     gridSize: 80,
    //     maxZoom: 18,
    //     styles: styles, // 应用自定义样式
    // });

    customMarker = new AMap.Icon({
        image: location,
        size: new AMap.Size(40, 40),
        imageSize: new AMap.Size(40, 40)
    });

    map.on('dragend', function (event) {
        // console.log("drag  event  ==>", event)
        // setMarkerClusterer(zoomLevelValue.value, [event.lnglat.lng, event.lnglat.lat])
    })

    map.on('zoomend', function (e) {
        // console.log('zoomend options.center ：', e.target.options.center);
        // 获取当前地图的缩放级别
        var zoomLevel = map.getZoom();
        // console.log("zoomLevelValue.value ==>", zoomLevel)
        if (zoomLevel >= 18) {
            // map.remove(marker);
        }
        // console.log("zoomLevelValue.value ==>", zoomLevelValue.value)
        // console.log("zoomLevelValue. zoomLevel ==>", zoomLevel)
        // // 执行你需要的操作，例如更新UI或者发送数据到服务器
        // // console.log('当前地图缩放级别为：' + zoomLevel);
        // zoomLevelValue.value = zoomLevel
        // var bounds = map.getBounds(); // 获取视野边界
        // // console.log('bounds ', bounds);
        // var ne = bounds.northEast; // 东北角经纬度
        // var sw = bounds.southWest; // 西南角经纬度

        // if (zoomLevel > 17 || Math.abs(zoomLevelValue.value - zoomLevel) < 1) {
        //     return
        // }
        // // 输出经纬度信息
        // console.log('东北角(右上角)经纬度：', ne.lat, ne.lng);
        // console.log('西南角(左下角)经纬度：', sw.lat, sw.lng);
        // cluster.setMaxZoom(zoomLevel);

        // emit('zoomChange', zoomLevel, e.target.options.center)

    });

    // setLayerData()
}
// const markersClusterer = ref([])
// const setMarkersData = (data) => {
//     if (data.length == 0) {
//         return
//     }
//     setMarkerClusterer(data)

// }

const setMarkerClusterer = async (value) => {
    try {
        let markersClusterer = []
        const result = await getData('defectsallLnglatDataInfo');
        const newDefects = value.map(item => {
            return {
                id: item.id,
                lnglat: [item.longitude, item.latitude],
                ...item
            }
        })
        if (result.content) {
            markersClusterer = [...newDefects, ...JSON.parse(result.content)]
        } else {
            markersClusterer = [...newDefects]
        }

        // console.log(" result  555 ==>", markersClusterer.value)
        // markersClusterer.value = value
        // console.log("markers ==>", markersClusterer.value)
        styleList = [
            {
                url: "https://a.amap.com/jsapi_demos/static/images/green.png",
                size: new AMap.Size(32, 32),
                offset: new AMap.Pixel(-16, -16),
                textColor: '#FFFFFF',
            },
            {
                url: "https://a.amap.com/jsapi_demos/static/images/orange.png",
                size: new AMap.Size(36, 36),
                offset: new AMap.Pixel(-18, -18),
                textColor: '#FFFFFF',
            },
            {
                url: "https://a.amap.com/jsapi_demos/static/images/darkRed.png",
                size: new AMap.Size(48, 48),
                offset: new AMap.Pixel(-24, -24),
                textColor: '#FFFFFF',
            },
            {
                url: "https://a.amap.com/jsapi_demos/static/images/darkRed.png",
                size: new AMap.Size(48, 48),
                offset: new AMap.Pixel(-24, -24),
                textColor: '#FFFFFF',
            },
            {
                url: "https://a.amap.com/jsapi_demos/static/images/darkRed.png",
                size: new AMap.Size(48, 48),
                offset: new AMap.Pixel(-24, -24),
                textColor: '#FFFFFF',
            },
            {
                url: "https://a.amap.com/jsapi_demos/static/images/darkRed.png",
                size: new AMap.Size(48, 48),
                offset: new AMap.Pixel(-24, -24),
                textColor: '#FFFFFF',
            },
            {
                url: "https://a.amap.com/jsapi_demos/static/images/darkRed.png",
                size: new AMap.Size(48, 48),
                offset: new AMap.Pixel(-24, -24),
                textColor: '#FFFFFF',
            },
            {
                url: "https://a.amap.com/jsapi_demos/static/images/darkRed.png",
                size: new AMap.Size(48, 48),
                offset: new AMap.Pixel(-24, -24),
                textColor: '#FFFFFF',
            },
            {
                url: "https://a.amap.com/jsapi_demos/static/images/darkRed.png",
                size: new AMap.Size(48, 48),
                offset: new AMap.Pixel(-24, -24),
                textColor: '#FFFFFF',
            },
            {
                url: "https://a.amap.com/jsapi_demos/static/images/darkRed.png",
                size: new AMap.Size(48, 48),
                offset: new AMap.Pixel(-24, -24),
                textColor: '#FFFFFF',
            }
        ];
        if (cluster) {
            cluster.setMap(null);
        }
        cluster = new AMap.MarkerClusterer(map, markersClusterer, {
            gridSize: 80,
            maxZoom: 18,
            styles: styleList,
        });

        cluster.on("click", (event) => {
            const { target, lnglat, clusterData } = event;
            // console.log("非聚合点标记被点击 111", clusterData);
            if (target instanceof AMap.MarkerClusterer) {
                if (clusterData.length > 1) {
                    // 聚合点
                    const zoom = map.getZoom();
                    map.setZoomAndCenter(zoom + 2, lnglat);
                    // console.log('聚合点标记被点击', event);
                } else {
                    // 非聚合点标记
                    // console.log("非聚合点标记被点击", clusterData);
                    if (clusterData.length == 0) {
                        return;
                    }
                    emit('clickMarker', clusterData[0])
                }
            }
        });
        cluster.setMap(map);
    } catch (error) {

    }
}

onMounted(() => {
    setTimeout(() => {
        initMap();
    }, 1000)
})

const moveToMarker = (extra: any) => {
    // 传入经纬度，设置地图中心点 
    var position = new AMap.LngLat(extra.longitude, extra.latitude);  // 标准写法
    // 简写 var position = [116, 39]; 
    if (!map) {
        return
    }
    map.setCenter(position);
    map.setZoomAndCenter(20, position);

    if (marker) {
        marker.setMap(null);
    }
    // 创建新的自定义标记
    marker = new AMap.Marker({
        map: map,
        position: position, // 设置标记位置为点击的经纬度
        icon: customMarker, // 设置标记的图标为自定义图标
        offset: new AMap.Pixel(-20, -37), // 设置标记的偏移量，使得标记点对准点击处
    });
    marker.setzIndex(-100);
    map.add(marker)
}


// const doubleClickAndMoveToMarker = (extra: any) => {
//     // 传入经纬度，设置地图中心点
//     var position = new AMap.LngLat(extra.longitude, extra.latitude);  // 标准写法
//     map.setCenter(position);
//     map.setZoomAndCenter(20, position);

//     if (marker) {
//         marker.setMap(null);
//     }
//     // 创建新的自定义标记
//     marker = new AMap.Marker({
//         map: map,
//         position: position, // 设置标记位置为点击的经纬度
//         icon: customMarker, // 设置标记的图标为自定义图标
//         offset: new AMap.Pixel(-20, -37), // 设置标记的偏移量，使得标记点对准点击处
//     });
//     marker.setzIndex(-100);
//     map.add(marker)

// }


defineExpose({
    moveToMarker,
    // doubleClickAndMoveToMarker,
    // setMarkersData,
    // updateClusterNumber
})
</script>

<style lang="scss" scoped>
h3 {
    margin: 40px 0 0;
}

ul {
    list-style-type: none;
    padding: 0;
}

li {
    display: inline-block;
    margin: 0 10px;
}

a {
    color: #42b983;
}

#mapContainer {

    height: 100%;
    width: 100%;


}
</style>